<?php
/**
 * Spaph_View
 *
 * The Spaph view() method proxies this class.
 */
class Spaph_View
{
    private $_plugins  = array();
    public  static $VIEW_ROOT_DIR = '';
    public  static $GLOBAL_VARS = array(); // set associative array

    public function __construct($plugins=array())
    {
        $this->_plugins = $plugins; // Array of plugin objects with _filter methods.
    }

    /**
     * Set global variables available to *ALL* Spaph_View objects.
     *
     * @param array $vars
     */
    public static function setViewVars($vars)
    {
        self::$GLOBAL_VARS = array_merge(self::$GLOBAL_VARS,$vars);
    }

    /**
     * Set the root directory of all views.
     *
     * @param string $dir
     */
    public static function setViewDir($dir)
    {
        $parts  = preg_split( '/[\\\\\/]+/', trim(rtrim($dir,'\\/')) );
        self::$VIEW_ROOT_DIR = implode(DIRECTORY_SEPARATOR,$parts) . DIRECTORY_SEPARATOR;
    }

    /**
     * This is a simple wrapper around render(), so the user doesn't
     * have to use a print statement.
     *
     * @param string $file
     */
    public function output($file)
    {
        echo $this->render($file);
    }

    /**
     * Render a template file. This method will buffer the results
     * of the required file then feed the input into any filters.
     *
     * @param string $filename
     * @return string
     */
    public function render($filename)
    {
        // Let's render the template.
        ob_start();

        // Extract global view vars in spaph.
        extract( self::$GLOBAL_VARS );

        // Extract public properties/values from $this
        extract( Spaph_View_Vars::getVars($this) );

        // Evaluate the template.
        require is_file($filename) ? $filename : self::$VIEW_ROOT_DIR.$filename;

        // Close buffer and get rendered results.
        $result = ob_get_clean();

        // Call any _filter() methods.
        foreach($this->_plugins as $plugin) {
            $result = $plugin->_filter($result);

            if(!is_string($result))
                throw new Exception("_filter() must return a string.");
        }

        return $result;
    }
}


